package com.t235.gc.configs.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }
    //自定义过滤器
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp,
                                    FilterChain chain) throws IOException, ServletException {
        HttpSession session = req.getSession();
        String id = session.getId();
        log.debug(id+";;;");
        if(id==null){
            return;
        }
    }
    //这里从token中获取用户信息并新建一个token
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) {
        String token=tokenHeader.replace(JwtTokenUtil.TOKEN_PREFIX,"");
        String username=JwtTokenUtil.getUsername(token);
        List<String> roles=JwtTokenUtil.getUserRole(token);
        Collection<GrantedAuthority> authorities=new ArrayList<>();
        roles.forEach(role->{
            authorities.add(new SimpleGrantedAuthority(role));
        });
        if(username!=null){
            return new UsernamePasswordAuthenticationToken(username,null,authorities);
        }
        return null;
    }
}
